<?php
namespace app\share\controller;

use think\Controller;

class Install extends Controller
{
    public function index()
    {
        $this->isInstall();
        //检查环境
        $args = [];
        $args['workWrite'] = is_writable('./config/database.php');
        $args['workFunction'] = function_exists(mysqli_connect);
        $args['rootUrl'] = $this->request->rootUrl();
        if($args['workWrite'] && $args['workFunction']){
            $args['install'] = true;
        }else{
            $args['install'] = false;
        }
        $this->assign($args);
        //加载模板
        return $this->fetch('./widget/install/index.tpl');
    }

    public function save()
    {
        //安装权限
        $this->isInstall();
        
        //写入权限验证
        if(!is_writable('./config/database.php')){
            $this->error('./config/database.php没有写入权限'); 
        }
        
        //验证函数
        if(!function_exists(mysqli_connect)){
            $this->error('mysqli_connect函数已被禁用，请先开启');
        }

        //MYSQL配置
        $data = [
            'type'            => 'mysql',
            'hostname'        => input('post.mysql_hostname/s', '127.0.0.1'),
            'database'        => input('post.mysql_database/s', 'daicuo'),
            'username'        => input('post.mysql_username/s', 'root'),
            'password'        => input('post.mysql_password/s', 'root'),
            'hostport'        => input('post.mysql_port/d', '3306'),
            'prefix'          => input('post.mysql_prefix/s', 'dc_'),
        ];

        //验证MYSQL连接参数
        $connect = @mysqli_connect($data['hostname'].":".intval($data['hostport']), $data['username'], $data['password']);
        if(mysqli_connect_errno($connect)){
            $this->error('连接MySQL失败：'.mysqli_connect_error());
        }
        //修改数据库连接字符集
        mysqli_set_charset($connect, "utf8mb4");
        //数据库不存在,尝试建立
        if( !@mysqli_select_db($data['database']) ){
             //创建数据库语句
			 mysqli_query($connect, "CREATE DATABASE `".$data["database"]."` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci");
            //数据库创建失败
            if( !@mysqli_select_db($connect, $data['database']) ){
                $this->error('数据库不存在且没有创建数据库的权限，请先手动创建后再安装。');
            }
        }
        
        //执行SQL
        $this->exceSql($connect,$data['prefix']);
        
        //关闭MYSQL链接
        mysqli_close($connect);

        //合并初始参数
        $data = array_merge(config('database.'),$data);
        
        //修改MYSQL连接配置
        dcWriteArray('./config/database.php', $data);

        //增加锁文件
        touch('./runtime/db/install.lock');

        //安装成功
        $this->success('安装成功', '/');
    }

    private function exceSql($connect='',$prefix='')
    {
        $sqls = file_get_contents('./runtime/db/install.sql');

        $sqls = str_replace('PREFIX_', $prefix, $sqls);
        
        $sqlArray = explode(';n', str_replace(array(";\r\n", ";\r", ";\n"), ";n", $sqls));
        
        foreach($sqlArray as $sql){
            if($sql){
                mysqli_query($connect, $sql);
            }
        }
    }

    private function isInstall()
    {
        if( is_file('./runtime/db/install.lock') ){
			$this->error('请勿重复安装！','/');
		}
    }
}